package core;


import core.StdNode;
import core.OutPort;
import core.TriggerPort;
import java.lang.reflect.Method;

/**
 *
 * @author Wijnand
 */
public class ReflectNode<T> extends StdNode {
	final T pojo;
	
	public ReflectNode(T pojo_)
	{
		this.pojo = pojo_;
		// no-arg function (getter...) -> outport
		// no-arg procedure -> trigger
		// (arg-function -> outport + inputport)
		// (arg-procedure -> trigger + inputport)
		
		for (final Method m : pojo.getClass().getMethods())
		{
			if (m.getParameterTypes().length==0)
			{
				if (m.getReturnType() == void.class)
				{
					//System.out.println("proc: " + m.getName());
					TriggerPort tp = new TriggerPort()
					{
						@Override
						public void callInternal() {
							try {
								m.invoke(pojo);
							}
							catch(Exception e) { 
								throw new RuntimeException(e); 
							}
						}
					};
					this.putPort(m.getName(), tp);
				}
				else	// returntype not void
				{ 
					//System.out.println("func: " + m.getName());
					OutPort op = new OutPort(m.getReturnType())
					{
						@Override
						public Object getValueInternal()
						{
							try {
								return m.invoke(pojo);
							} 
							catch (Exception e) {
								throw new RuntimeException(e);
							}
						}

						@Override
						public DispatcherPort getValueChangedPort() {
							return null;
						}
					};
					this.putPort(m.getName(), op);
				}
			}	
		}
	}
	
	
	
}
